package com.chinaunicom.beanfactorypostprocessor;

import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/12/12 11:14
 * Description:
 */
public class HelloBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

	@Override
	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {
		//获取所有的beanName
		String beanNames[] = beanFactory.getBeanDefinitionNames();
		if (beanNames != null && beanNames.length > 0) {
			BeanDefinition beanDef = null;
			for (String beanName : beanNames) {
				//获取对应的bean定义
				beanDef = beanFactory.getBeanDefinition(beanName);
				if (beanName.equals("cat")) {
					beanDef.getPropertyValues().addPropertyValue("date", "2021-12-12 11:32");
				}
				this.printBeanDef(beanName, beanDef);
			}
		}
	}


	/**
	 * 打印bean定义的基本信息
	 *
	 * @param beanName
	 * @param beanDef
	 */
	private void printBeanDef(String beanName, BeanDefinition beanDef) {
		StringBuilder defStr = new StringBuilder("beanName: ").append(beanName);
		defStr.append(", className: ").append(beanDef.getBeanClassName());
		defStr.append(", scope: ").append(beanDef.getScope());
		defStr.append(", parent: ").append(beanDef.getParentName());
		defStr.append(", factoryBean: ").append(beanDef.getFactoryBeanName());
		defStr.append(", factoryMethod: ").append(beanDef.getFactoryMethodName());
		defStr.append(", bean definition: ");
		List<PropertyValue> collect = Arrays.stream(beanDef.getPropertyValues().getPropertyValues()).collect(Collectors.toList());
		if (!ObjectUtils.isEmpty(collect)) {
			MutablePropertyValues propertyValues = beanDef.getPropertyValues();
			defStr.append("[ ");
			collect.forEach(v -> {
				// 获取该bean下的所有beanDefinition信息
				String name = v.getName();
				Object value = v.getValue();
				defStr.append(name + "-" + value);
			});
			defStr.append("]");

		}
		System.out.println(defStr);
	}
}
